<script setup>
import _ from 'lodash';
import {computed, onMounted, reactive, ref, toRefs, watch} from "vue";
import {isGroup, isApp, isMbRoot, canEdit} from './common.js';
import {useCommonStore} from "@jzl/stores";
import {$jui, $utils} from '@jzl/utils'
import {api} from "@jzl/api";

const DEFAULT_FORM = {
  project_id: -1,    // _.get(this.project, 'project_id'),
  parent_id: -1,      // _.get(this.currentData, 'mb_group_id', -1),
  app_id: -1,      // module_id,
  name: '',
  remark: ''
}
const emit = defineEmits(['close']);
const props = defineProps({
  actionType: {
    type: String,
    default: 'view'
  },
  currentData: {
    type: Object,
    default: () => {
    }
  }
})

const loading = ref(false)
const form = ref(_.cloneDeep(DEFAULT_FORM))

watch(() => [props.actionType, props.currentData], () => {
  init()
}, {deep: true});

onMounted(() => {
  init();
})

const init = () => {
  let iForm = null;
  if(props.actionType === 'create') {
    let app_id = -1;

    if(isGroup(props.currentData)) {
      app_id = props.currentData.app_id;
    } else {
      app_id = _.get(props.currentData, 'id') || _.get(props.currentData, 'group_id');
    }

    iForm = {
      project_id: useCommonStore().project?.project_id,
      parent_id: _.get(props.currentData, 'mb_group_id', -1),
      app_id: app_id || -1,
      name: '',
      remark: ''
    }
  } else {
    iForm = _.cloneDeep(props.currentData);
  }

  form.value = iForm;
}

const handleSubmitCreateGroup = async () => {

  let ret = null;
  let kv = _.cloneDeep(form.value);

  loading.value = true;

  if(form.value.mb_group_id) {
    ret = await api.mb.updateMbGroup(kv);
  } else {
    ret = await api.mb.createMbGroup(kv);
  }

  loading.value = false;

  if(ret) {
    $jui.toast('操作成功！');
    handleCancel(true);
  }
}

const handleCancel = (flat) => {
  emit('close', flat);
}
</script>

<template>
    <el-form
      ref="formRef"
      label-width="100px">
        <el-form-item label="名称">
            <el-input
              v-model="form.name"
              :disabled="actionType === 'view'"
            ></el-input>
        </el-form-item>
        <el-form-item label="备注">
            <el-input
              type="textarea"
              :rows="2"
              v-model="form.remark"
              :disabled="actionType === 'view'"
            ></el-input>
        </el-form-item>
        <el-form-item label="">
            <el-button
              v-if="actionType !== 'view'"
              type="primary"
              size="default"
              @click="handleSubmitCreateGroup()"
            > 提交 </el-button>
            <el-button
              size="default"
              @click="handleCancel()"
            > 取消 </el-button>
        </el-form-item>
    </el-form>
</template>
